define(['jquery', 'bootstrap', 'backend', 'table', 'form','clipboard.min'], function ($, undefined, Backend, Table, Form, ClipboardJS) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
             Table.api.init({
                extend: {
                    teacher_url: 'sample/sample/teacher_list',
                    family_url: 'sample/sample/family_list',
                    promote_url: 'sample/sample/promote_list', 
                    
                }
            });
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.size() > 0) {
                    Controller.table[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });
     
            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
        },
        table: {
            teacher: function () {
                window.refresh = function(){
                    table1.bootstrapTable('refresh');
                }
                // 表格1
                var table1 = $("#teacher_table");
                table1.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.teacher_url,
                     extend: {

                        generate_url: 'sample/sample/send',
                        excel_url: 'sample/sample/send_excel',
                        check_url: 'sample/sample/send_one/type/1',
                        del_url: 'sample/sample/delete/type/1',
                        add_url: 'sample/sample/teacher_add',
                        edit_url: 'sample/sample/teacher_edit',
                        
                    },
                    toolbar: '#teacher_toolbar',
                    pk: 'id',
                    sortName: 'id',
                    searchFormVisible: true,
                    searchFormTemplate: 'customformtpl',
                    pageList: [10, 50, 100,300,500,1000,1500],
                    columns: [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('Id')},
                            {field: 'name', title: __('Name_n')},
                            {field: 'tel', title: __('Tel')},
                             {field: 'province', title: __('Area_s'), table: table1,formatter: Controller.api.formatter.province},
                            // {field: 'address', title: __('Address')},
                            {field: 'school', title: __('School')},
                            {field: 'grade_text', title: __('Grade')},
                             {field: 'post', title: __('Post')},
                             {field: 'gift_text', title: __('Gift')},
                            {field: 'receive_text', title: __('Receive'),events: Controller.api.events.statusName,formatter: Controller.api.formatter.statusName},
                               {field: 'message_text', title: __('Message_status'),events: Controller.api.events.messageStatus,formatter: Controller.api.formatter.MessageNum},
                            {field: 'source', title: __('Source')},
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                             {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate,formatter: Controller.api.formatter.operate},
                      
                       
                        ]
                    ]

                });

                // 为表格1绑定事件
                Table.api.bindevent(table1);
            },  
          family: function () {
                window.refresh = function(){
                    table2.bootstrapTable('refresh');
                }
                // 表格1
                var table2 = $("#family_table");
                table2.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.family_url,
                     extend: {
                        generate_url: 'sample/sample/send',
                        excel_url: 'sample/sample/send_excel',
                        check_url: 'sample/sample/send_one/type/2',
                        del_url: 'sample/sample/delete/type/2',
                        add_url: 'sample/sample/family_add',
                        edit_url: 'sample/sample/family_edit',

                    },
                    toolbar: '#family_toolbar',
                    pk: 'id',
                    sortName: 'id',
                    searchFormVisible: true,
                     searchFormTemplate: 'customformtpl2',
                     pageList: [10, 50, 100,300,500,1000,1500],
                    columns: [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('Id')},
                            {field: 'name', title: __('Name_n')},
                            {field: 'tel', title: __('Tel')},
                            {field: 'province', title: __('Area_s'), table: table2,formatter: Controller.api.formatter.province},
                            // {field: 'address', title: __('Address')},
                            {field: 'school', title: __('School')},
                            {field: 'grade_text', title: __('Grade')},
                             {field: 'receive_text', title: __('Receive'),events: Controller.api.events.statusName,formatter: Controller.api.formatter.statusName},
                               {field: 'message_text', title: __('Message_status'),events: Controller.api.events.messageStatus,formatter: Controller.api.formatter.MessageNum},
                            {field: 'source', title: __('Source')},
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                            {field: 'operate', title: __('Operate'), table: table2, events: Table.api.events.operate,formatter: Controller.api.formatter.operate},
                        ]
                    ]
                });

                // 为表格1绑定事件
                Table.api.bindevent(table2);
            },
            promote: function () {
                 window.refresh = function(){
                    table3.bootstrapTable('refresh');
                }
                // 表格1
                var table3 = $("#promote_table");
                table3.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.promote_url,
                    extend: {
                        generate_url: 'sample/sample/send',
                        excel_url: 'sample/sample/send_excel',
                        check_url: 'sample/sample/send_one/type/3',
                        del_url: 'sample/sample/delete/type/3',
                        add_url: 'sample/sample/promote_add',
                        edit_url: 'sample/sample/promote_edit',
                    },
                    toolbar: '#promote_toolbar',
                    pk: 'id',
                    sortName: 'id',
                    searchFormVisible: true,
                     searchFormTemplate: 'customformtpl2',
                     pageList: [10, 50, 100,300,500,1000,1500],
                    columns: [
                        [
                             {checkbox: true},
                            {field: 'id', title: __('Id')},
                            {field: 'name', title: __('Name_n')},
                            {field: 'tel', title: __('Tel')},
                             {field: 'province', title: __('Area_s'), table: table3,formatter: Controller.api.formatter.province},
                            // {field: 'address', title: __('Address')},
                            {field: 'school', title: __('School')},
                              {field: 'grade_text', title: __('Grade')},
                            {field: 'receive_text', title: __('Receive'),events: Controller.api.events.statusName,formatter: Controller.api.formatter.statusName},
                            {field: 'message_text', title: __('Message_status'),events: Controller.api.events.messageStatus,formatter: Controller.api.formatter.MessageNum},
                            {field: 'source', title: __('Source')},
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                            {field: 'operate', title: __('Operate'), table: table3, events: Table.api.events.operate,formatter: Controller.api.formatter.operate},
                        ]
                    ]
                });

                // 为表格1绑定事件
                Table.api.bindevent(table3);
            },

        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },  
        teacher_add: function () {
            Controller.api.bindevent();
        },   
        family_add: function () {
            Controller.api.bindevent();
        },  
        promote_add: function () {
            Controller.api.bindevent();
        },
        teacher_edit: function () {
            Controller.api.bindevent();
        },   
        family_edit: function () {
            Controller.api.bindevent();
        },  
        promote_edit: function () {
            Controller.api.bindevent();
        },
        send: function () {
            Controller.api.bindevent();
            $("#submitbtn").on("click", function(){
             var that = this;
              Layer.confirm(
                    __('确认发送吗?'),
                    {icon: 3, title: __('Warning'),  shadeClose: true},
                    function (index) {
                         Layer.close(index);
                         $(that).closest("form").trigger("submit");
                    }
                );
            });
        },    
        send_one: function () {
            Controller.api.bindevent();
            $("#submitbtn").on("click", function(){
                 var that = this;
                  Layer.confirm(
                        __('确认发送吗?'),
                        {icon: 3, title: __('Warning'),  shadeClose: true},
                        function (index) {
                             Layer.close(index);
                             $(that).closest("form").trigger("submit");
                        }
                    );

                    
                });
        },        
        send_excel: function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                 if(data == 1){
                    console.log(ret.url);
                    var str = ret.msg;
                    str += '<br><a class="btn-copy" data-clipboard-text="'+ret.url+'" href="javascript:;" >点击复制失败excel链接,通过浏览器打开</a>';
                    Layer.alert(str, {
                      closeBtn: 0,
                      btn: [__('点击下载')],
                      title: '导出失败excel',
                    }, function(){
                        document.location.href = ret.url;
                        top.Toastr.success(ret.msg);
                        parent.refresh();
                        Fast.api.close(data);
                    });
                    return false;
                  }
            }, function(data, ret){
                console.log('错误');
            });
            $("#submitbtn").on("click", function(){
                 var that = this;
                  Layer.confirm(
                        __('确认发送吗?'),
                        {icon: 3, title: __('Warning'),  shadeClose: true},
                        function (index) {
                             Layer.close(index);
                             $(that).closest("form").trigger("submit");
                        }
                    );

                    
                });
            var clipboard = new ClipboardJS('.btn-copy');
            clipboard.on('success', function(e) {
                alert("复制成功");
                // console.info('Action:', e.action);
                // console.info('Text:', e.text);
                // console.info('Trigger:', e.trigger);
            });
            clipboard.on('error', function(e) {
                alert("复制失败,请重试或直接下载");
                // console.error('Action:', e.action);
                // console.error('Trigger:', e.trigger);
            });
      
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
                 province: function (value, row, index) {
                    var areatext = '';
                    if(value){
                        areatext = Config.arealist[value];
                        if(row['city']){
                             areatext +=' '+Config.arealist[row['city']];
                            if(row['area']){
                                areatext +=' '+Config.arealist[row['area']];
                            }
                        }
                    }
                  return areatext;
                },
                statusName: function (value, row, index) {
                 if(row.receive == 2 && (row.receive_time || row.sweep_publish)){
                     return '<a class="btn btn-xs btn-dialog btn-ip"> '+row.receive_text+ '</a>';
                 }else{
                     return row.receive_text;
                 }
                },         
                MessageNum: function (value, row, index) {
                   if(row.message_status == 2 && row.message_time){
                     return '<a class="btn btn-xs btn-dialog btn-message"> '+value+' 次数:'+row['message_num']+ '</a>';
                 }else{
                     return value+' 次数:'+row['message_num'];
                 }  
                  
                },
                operate: function (value, row, index) {
                    var table = this.table;
                    // 操作配置
                    var options = table ? table.bootstrapTable('getOptions') : {};
                    // 默认按钮组
                    var buttons = $.extend([], this.buttons || []);
                   
                   
                    if (options.extend.edit_url !== ''){
                        buttons.push({
                            name: 'edit',
                            icon: 'fa fa-pencil',
                            title: __('Edit'),
                            extend: 'data-toggle="tooltip"',
                            classname: 'btn btn-xs btn-success btn-editone',
                            url: options.extend.edit_url
                        });
                    }
                    if (options.extend.check_url !== ''){
                            buttons.push({
                                name: 'books',
                                icon: 'fa fa-paper-plane',
                                title: __('Send'),
                                extend: 'data-toggle="tooltip"',
                                area:['50%', '80%'],
                                classname: 'btn btn-xs btn-success btn-checksample',
                                url: options.extend.check_url
                            });
                     }
                     if (options.extend.del_url !== '') {
                            buttons.push({
                                name: 'del',
                                icon: 'fa fa-trash',
                                title: __('Del'),
                                extend: 'data-toggle="tooltip"',
                                classname: 'btn btn-xs btn-danger btn-delone',
                                url: options.extend.del_url
                            });
                        }
                    return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                },
          },
          events: {//绑定事件的方法
                statusName: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var str = '';
                        if(row.receive_time){
                           str += __('Receive_time')+": <code>" +Moment(parseInt(row.receive_time) * 1000).format("YYYY-MM-DD HH:mm:ss")+ "</code>";
                        }
                        if(row.sweep_publish){
                          str += "<br/>扫码人: <code>" + Config.userlist[row['sweep_publish']].username + "</code>";
                        }
                        Layer.alert(str);
                    }
                },
                 messageStatus: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-message': function (e, value, row, index) {
                        e.stopPropagation();
                        var str = '';
                        if(row.message_time){
                           str += __('Message_time')+": <code>" +Moment(parseInt(row.message_time) * 1000).format("YYYY-MM-DD HH:mm:ss")+ "</code>";
                        }
                        Layer.alert(str);
                    }
                }
            }
        }
    };
    return Controller;
});